
package GUI;


import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.Highlighter.HighlightPainter;
import javax.swing.tree.*;
import java.util.*;
import javax.swing.plaf.metal.MetalIconFactory;
import BUS.*;
import DAO.DataManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter.Highlight;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;




public class Server extends JFrame implements ActionListener,PopupMenuListener
     {
    
    //
    public boolean OpenConnect = false;
    
    //Khởi tạo các biến
    private JLabel label;
    private JTextArea textArea;
    private JTextArea textBottom;
    private  JToolBar toolBar;//Toolbar
    private   SplitPanelRight splitPaneRight ;//right of main Splitpane
    private  JSplitPane splitPane ;
    private  JScrollPane scrollPane ;
    private  JScrollPane scrollPaneBottom;
   
  // start Toolbar
    static final private String save = "save";
    static final private String newquery = "newquery";
    static final private String open = "open";
    static final private String run = "runcommand";    
    
    JButton jbtnnewq;
    JButton jbtnsave;
    JButton jbtnrun;
    JButton jbtnopen;
    Choice select_database;
     
  //end Toolbar 
   //start tree
     private JTree jtree;
     private JTable jtable;
    
    //end tree
  //popupmenu
   private JPopupMenu popup_database;
   private JPopupMenu popup_table; 
   private JPopupMenu popup_server;
   private  Point loc;
  //popupmenu  
   //start menu bar
   private JMenuBar menuBar;
   private JMenu menu;
   private JMenuItem menuItem;
   
   
    public Server() {
      //  super("SplitPaneDemo2");
           super();
   
   

        //Create the menu bar.
      menuBar = new JMenuBar();

        //Build the first menu.
      menu = new JMenu("File");
      menu.setMnemonic(KeyEvent.VK_F);
       
      menuBar.add(menu);

        //a group of JMenuItems
       menuItem = new JMenuItem("Open File",
                                 KeyEvent.VK_O);
       menuItem.setActionCommand("OPEN FILE");
       menuItem.addActionListener(this);
        menu.add(menuItem);
       menuItem = new JMenuItem("Open Connect",
                                 KeyEvent.VK_O);
       menuItem.setActionCommand("OPEN CONNECT");
       menuItem.addActionListener(this);
 
       menu.add(menuItem);
       
       menuItem = new JMenuItem("Save File",
                                 KeyEvent.VK_S);
       menuItem.setActionCommand("SAVE FILE");
       menuItem.addActionListener(this);
       menu.add(menuItem);
       
       menuItem = new JMenuItem("Exit",
                                 KeyEvent.VK_E);
        menuItem.setActionCommand("EXIT"); 
       menuItem.addActionListener(this);
       menu.add(menuItem);
   
        //Build second menu in the menu bar.
        menu = new JMenu("Edit");
        menu.setMnemonic(KeyEvent.VK_E);
       
        menuBar.add(menu);
        menu = new JMenu("Help");
        menu.setMnemonic(KeyEvent.VK_H);
        menuBar.add(menu);
        setJMenuBar(menuBar);
        
 // end menu bar
  // start Toolbar
        toolBar = new JToolBar("Still draggable");
        addButtons(toolBar);
       
       textBottom = new JTextArea(40,130);
       scrollPaneBottom = new JScrollPane(textBottom);
       getContentPane().add(toolBar, BorderLayout.PAGE_START);
        //add(scrollPane, BorderLayout.CENTER);
  //end Toolbar      
        loadTree();//contructor tree node
     
  //start split pannel 
      splitPaneRight = new SplitPanelRight();
    JSplitPane right = splitPaneRight.getSplitPane();  
     right.setBorder(null);
     
     JScrollPane treepanel = new JScrollPane(jtree);
     splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                                               treepanel,right); 
     
   //end split pannel      
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(180);
    
    right.setMinimumSize(new Dimension(100, 50));
   
     getContentPane().add(splitPane);
     Toolkit kit = Toolkit.getDefaultToolkit();
     Dimension screenSize = kit.getScreenSize();
     setPreferredSize(screenSize);   
   // splitPaneRight.getPanelTop().add(scrollPane);   
      
         
    }
   protected void addButtons(JToolBar toolBar) {
       
        //first button
        jbtnnewq = makeNavigationButton("new",newquery,
                                      "new query");
        
        toolBar.add(jbtnnewq);

        //second button
        jbtnsave = makeNavigationButton("save",save,
                                      "save");
        toolBar.add(jbtnsave);
         jbtnsave.setEnabled(false);
        //third button
        jbtnopen = makeNavigationButton("open",open,
                                      "open file");
         toolBar.add(jbtnopen);
         //four button 
        jbtnrun = makeNavigationButton("RunIcon", run,
                                      "Run sql");
        toolBar.add(jbtnrun);
       
        jbtnrun.setEnabled(false);
        //create a choice
      
         DataManager d  = new DataManager();
         d.ReadDatabase();
        select_database = new Choice();
        for(int i = 0; i < d.count_database; i++)
        {
            select_database.addItem(d.Database_Arr[i].Name);
        }
         select_database.setMaximumSize(new Dimension(120,30));
        toolBar.add(select_database);
         
       
    }
  // create Jbutton for tollbar
    protected JButton makeNavigationButton(String imageName,
                                           String actionCommand,
                                           String toolTipText)
                                           {
        //Look for the image.
        String imgLocation = "images/"
                             + imageName
                             + ".png";
        URL imageURL = Server.class.getResource(imgLocation);
       
        //Create and initialize the button.
        JButton button = new JButton();
        button.setActionCommand(actionCommand);
        button.setToolTipText(toolTipText);
        button.addActionListener(this);

        if (imageURL != null) {                      //image found
            button.setIcon(new ImageIcon(imageURL));
        } else {                                     //no image found
           
            System.err.println("Resource not found: "
                               + imgLocation);
        }

        return button;
    }
  // manipulate event for Toolbar,righ click on tree
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        String databaseName = "";
        if(cmd.equals("OPEN FILE"))
        {
            
           
            setVisible(true);
            JFileChooser fc = new JFileChooser();
	    int returnVal = fc.showOpenDialog(null);
            String path = "";
            File inputFile;
	     if (returnVal == JFileChooser.APPROVE_OPTION) 
		  {
		      inputFile = fc.getSelectedFile();
		       path = inputFile.getPath();
                       jbtnsave.setEnabled(true);//set enable = false for jbtnsave and jbtnrun
                        jbtnrun.setEnabled(true);
                        textArea = new JTextArea(40,120);
                        scrollPane = new JScrollPane(textArea);
                        textArea.getDocument().addDocumentListener(new MyDocumentListener());
                        splitPaneRight.setSplitPaneTop(scrollPane);
		           
		    }
            InputStream in = null;
             try {
                 in = new FileInputStream(path);
                 } catch (FileNotFoundException ex) {
                        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                     }
                  try {
                      textArea.read(new InputStreamReader(in), null);
                      pack();
                    } catch (IOException ex) {
                         ex.printStackTrace();
                         } 
        }
        else
            if(cmd.equals("OPEN CONNECT"))
            {
               // xử ;ý trong này nhé
               if(!OpenConnect)
               {
                   OpenConnect = true;
                   OpenConnect open = new OpenConnect();
                   open.setVisible(true);
               }
                       
            }
           else
                if(cmd.equals("SAVE FILE"))
                    {
                            String content = textArea.getText();
                             JFileChooser fc = new JFileChooser();
				fc.setSelectedFile(new File("sql.txt"));
				int returnVal = fc.showSaveDialog(null);
				if (returnVal == JFileChooser.APPROVE_OPTION) 
                                      {
				 
				    FileOutputStream fos;
					try {
						fos = new FileOutputStream(fc.getSelectedFile());
                                                PrintWriter output=new PrintWriter(fos,true);
							//fos.write(content);
						      output.println(content);
							fos.close();
                                                        output.close();
							JOptionPane.showMessageDialog(null, "Save file sucessfully!");

					} catch (FileNotFoundException ex) {
						// TODO Auto-generated catch block
						ex.printStackTrace();
						JOptionPane.showMessageDialog(null, "Error when save file. Please try again.");

					}catch (IOException ex) {
						// TODO Auto-generated catch block
						ex.printStackTrace();
						JOptionPane.showMessageDialog(null, "Error when save file. Please try again.");
					}

		                }
                     }
           else
             if(cmd.equals("EXIT"))
             {
                
               System.exit(0);
             }
            
       // manipulate button of toolbar
            else if (newquery.equals(cmd)) { //first  toobar button new query clicked
             textArea = new JTextArea(40,120);
             scrollPane = new JScrollPane(textArea);
             textArea.getDocument().addDocumentListener(new MyDocumentListener());
             splitPaneRight.setSplitPaneTop(scrollPane);
             pack();
             setVisible(true);
             jbtnsave.setEnabled(false);
             jbtnrun.setEnabled(false);
         
        } else if (save.equals(cmd)) { // second toobar button save clicked
            {             
                         String content = textArea.getText();
                          JFileChooser fc = new JFileChooser();
				fc.setSelectedFile(new File("sql.txt"));
				int returnVal = fc.showSaveDialog(null);
				if (returnVal == JFileChooser.APPROVE_OPTION) 
                                      {
				 
				    FileOutputStream fos;
					try {
						fos = new FileOutputStream(fc.getSelectedFile());
                                                PrintWriter output=new PrintWriter(fos,true);
							//fos.write(content);
						   output.println(content);
							fos.close();
                                                        output.close();
							JOptionPane.showMessageDialog(null, "Save file sucessfully!");

					} catch (FileNotFoundException ex) {
						// TODO Auto-generated catch block
						ex.printStackTrace();
						JOptionPane.showMessageDialog(null, "Error when save file. Please try again.");

					}catch (IOException ex) {
						// TODO Auto-generated catch block
						ex.printStackTrace();
						JOptionPane.showMessageDialog(null, "Error when save file. Please try again.");
					}

		                }
        }
        } else if(open.equals(cmd))
        {
            
            JFileChooser fc = new JFileChooser();
	    int returnVal = fc.showOpenDialog(null);
            String path = "";
            File inputFile;
	     if (returnVal == JFileChooser.APPROVE_OPTION) 
		  {
		      inputFile = fc.getSelectedFile();
		            
		       path = inputFile.getPath();
                       jbtnsave.setEnabled(true);//set enable = false for jbtnsave and jbtnrun
                        jbtnrun.setEnabled(true);
                         textArea = new JTextArea(40,120);
                         scrollPane = new JScrollPane(textArea);
                          textArea.getDocument().addDocumentListener(new MyDocumentListener());
                         splitPaneRight.setSplitPaneTop(scrollPane);
                         pack();
                         setVisible(true);
                
		    }
           InputStream in = null;
             try {
                 in = new FileInputStream(path);
                 } catch (FileNotFoundException ex) {
                        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                     }
                  try {
                      textArea.read(new InputStreamReader(in), null);
                    } catch (IOException ex) {
                         ex.printStackTrace();
                         } 
        }
        else if (run.equals(cmd)) { // third toobarr button run clicked
               
         BUS_ParseQuerry demo = null; 
        
         
         try
         {
            demo = new BUS_ParseQuerry(select_database.getSelectedItem());
            Bus_Table table1 =  (Bus_Table)demo.ParseQuerry( textArea.getSelectedText());
           
            DefaultTableModel  model_table = new DefaultTableModel();
             for(int j = 0;j<table1.tableData.elementAt(0).rowData.size();j++)
             {
               
                 model_table.addColumn(table1.tableData.elementAt(0).rowData.elementAt(j).columnName);
             }
           
        for(int i = 0;i<table1.tableData.size();i++)
         {
             Vector data = new Vector();
             for(int j = 0;j<table1.tableData.elementAt(i).rowData.size();j++)
             {
               
                  data.add(table1.tableData.elementAt(i).rowData.elementAt(j).Value);
             }
              model_table.addRow(data);
         }
       
       JTable jtable = new JTable();
       jtable.setModel(model_table);
       jtable.setPreferredScrollableViewportSize(new Dimension(table1.tableData.elementAt(0).rowData.size()*100,100));
       jtable.setFillsViewportHeight(true);
       
        //Create the scroll pane and add the table to it.
       JPanel jpanel = new JPanel();
       splitPaneRight.setSplitPaneBottom(jpanel);
       JScrollPane scrollPane_table = new JScrollPane(jtable);
       splitPaneRight.setSplitPaneBottom(scrollPane_table);
        pack();
        setVisible(true);
               
         }catch(Exception ex)
         {
            Font font = new Font("Times New Roman", Font.PLAIN, 13);
            Color collor = new Color(255,0,0);
            textBottom.setFont(font);
            textBottom.setForeground(collor);
               
             textBottom.setText(demo.Message_Error);
          
             textBottom.setEditable(false);
             System.out.println(ex.getMessage());
             splitPaneRight.setSplitPaneBottom(textBottom);
           
             pack();
             setVisible(true);
                       
         }    
        
        splitPaneRight.getSplitPane().setDividerLocation(500);
       
        }
        else // manipulate on popup menu 
        {
          TreePath path  = jtree.getPathForLocation(loc.x, loc.y);
            
         if(cmd.equals("DROP TABLE"))//manipulate event of Drop database
         {
           jbtnsave.setEnabled(false);//set enable = false for jbtnsave and jbtnrun
           jbtnrun.setEnabled(false);  
           dropTable(path.getParentPath().getLastPathComponent().toString(),path.getLastPathComponent().toString());
           loadTree();
           expand(jtree,path.getParentPath());
          splitPane.setLeftComponent(jtree);
          splitPane.setOneTouchExpandable(true);
          splitPane.setDividerLocation(180);
          
         }
         if(cmd.equals("DROP DATABASE"))
         {
          jbtnsave.setEnabled(false);//set enable = false for jbtnsave and jbtnrun
          jbtnrun.setEnabled(false);   
          dropDatabase(path.getLastPathComponent().toString());
          loadTree();
          expand(jtree,path.getParentPath());
          splitPane.setLeftComponent(jtree);
          splitPane.setOneTouchExpandable(true);
          splitPane.setDividerLocation(180);
         }
         if(cmd.equals("CREATE TABLE"))///manipulate event of Create Table
         {
            jbtnsave.setEnabled(false);//set enable = false for jbtnsave and jbtnrun
            jbtnrun.setEnabled(false);
             createTable(path.getLastPathComponent().toString());
         }
         if(cmd.equals("OPEN"))///manipulate event of OPen Table
         {
             jbtnsave.setEnabled(false);//set enable = false for jbtnsave and jbtnrun
            jbtnrun.setEnabled(false);
             String database = path.getParentPath().getLastPathComponent().toString();
             
             String table = path.getLastPathComponent().toString();
             OpenTable(table,database);
         }
         if(cmd.equals("CREATE DATABASE"))
         {
            jbtnsave.setEnabled(false);//set enable = false for jbtnsave and jbtnrun
            jbtnrun.setEnabled(false);
           boolean flag = false;
           do{
               databaseName = JOptionPane.showInputDialog("Please enter database name");
         
                if((checkInput(databaseName) == false))
                JOptionPane.showMessageDialog(this,"Database name invalid!","Anouncement",JOptionPane.WARNING_MESSAGE);
                   else
                     {
                         try{
                              DataManager d = new DataManager();
                               d.ReadDatabase();
                               flag =  d.CreateDatabase(databaseName);
                                if(!flag)
                                {
                                 JOptionPane.showMessageDialog(this,"Database has exits!","Anouncement",JOptionPane.WARNING_MESSAGE); 
                                  }
                                else
                                {
                                     JOptionPane.showMessageDialog(this,"Succeed!","Anouncement",JOptionPane.OK_OPTION); 
                                     select_database.addItem(databaseName);
                                }
                            }
                          catch(Exception ex)
                             {
                              JOptionPane.showMessageDialog(this,"Database has exits!","Anouncement",JOptionPane.WARNING_MESSAGE);
                                System.out.println(ex.getMessage());
                              }
                        }
                }
            while((checkInput(databaseName) == false) || flag == false);
         }
         if(cmd.equals("REFRESH"))
         {
            
          loadTree();
          splitPane.setLeftComponent(jtree);
          splitPane.setOneTouchExpandable(true);
          splitPane.setDividerLocation(180);
          DataManager d  = new DataManager();
          d.ReadDatabase();
          select_database.removeAll();
           for(int i = 0; i < d.count_database; i++)
             {
             select_database.addItem(d.Database_Arr[i].Name);
             }
          
         }
        }
    }
   // show GUI for main
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new Server();
     
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        frame.pack();
        frame.setVisible(true);
    }
   // run Program
    public static void main(String[] args) {
      
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    
    
    // expand tree
 public void expand(JTree tree, TreePath path) {
        TreeNode node = (TreeNode)path.getLastPathComponent();
        if (node.getChildCount() >= 0) {
            java.util.Enumeration e = node.children();
            while(e.hasMoreElements()) {
                TreeNode n = (TreeNode)e.nextElement();
                expand(tree, path.pathByAddingChild(n));
            }
        }
        tree.expandPath(path);
    }
 /*
  * @method checkInput check name dabase when we input
  * @parma databaseName : string
  * @return true if it hasn't empty char else return false
  */
 public Boolean checkInput(String databaseName)
 {
   
     if(databaseName.length() == 0)
         return false;
     for(int i = 0;i < databaseName.length();i++)
     {
         if(databaseName.charAt(i) == ' ')
              return false;
     }
     
     return true;
     
 }       
 // get data from database
    public IconNode getTreeComponent() {
     
     
     DataManager d  = new DataManager();
      d.ReadDatabase();
      int len = d.count_database;
      int increment_databases = 2;
      int increment_tables = 3;
      int increment_coumns = 4;
      for(int i = 0;i<d.count_database;i++)
      {
          len = len + d.Database_Arr[i].count_table;
       for(int j = 0;j<d.Database_Arr[i].count_table;j++)
             {
                 len = len + d.Database_Arr[i].Table_Name[j].count_colum;
                 
              }
      }
       IconNode[] nodes = new IconNode[len+2];
       nodes[0] = new IconNode("Server");
       nodes[0].setIcon(createImageIcon("images/server2.png"));
       nodes[1] = new IconNode("Database");
       nodes[1].setIcon(createImageIcon("images/forder.png"));
        nodes[0].add(nodes[1]);
         for(int i = 0;i<d.count_database;i++)
        {    // System.out.println(d.count_database);
              //System.out.println(d.Database_Arr[i].Name);
               nodes[increment_databases] = new IconNode(d.Database_Arr[i].Name);
               nodes[1].add(nodes[increment_databases]);
               nodes[increment_databases].setIcon(createImageIcon("images/database1.png"));
             for(int j = 0;j<d.Database_Arr[i].count_table;j++)
             {
               //  System.out.println(d.Database_Arr[i].Table_Name[j].Name);
                 nodes[increment_tables] = new IconNode(d.Database_Arr[i].Table_Name[j].Name);
                 nodes[increment_databases].add(nodes[increment_tables]);
                 nodes[increment_tables].setIcon(createImageIcon("images/table.jpg"));
                 for(int k = 0;k<d.Database_Arr[i].Table_Name[j].count_colum;k++)
                 {
                  
                      nodes[increment_coumns] = new IconNode(d.Database_Arr[i].Table_Name[j].Colum_name[k].Name);
                      nodes[increment_tables].add(nodes[increment_coumns]);
                      nodes[increment_coumns].setIcon(createImageIcon("images/column2.png"));
                      increment_coumns = increment_coumns + 1;
                     
                 }
                   increment_tables = increment_tables + 1;
              }
            increment_databases = increment_databases + 1;
       }
         
       return nodes[0];
    }
    /*
     * get Icon from Resurse
     * @param path : String
     * return ImageIcon if find else return NULL
     */
     protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = Server.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }
     /*
      * @method GetMenuItem : get MenuItem   use for pupup menu
      * @param s : String
      * return menuItem 
      */
    private JMenuItem getMenuItem(String s) {
        JMenuItem menuItem = new JMenuItem(s);
        menuItem.setActionCommand(s.toUpperCase());
        menuItem.addActionListener(this);
        return menuItem;
    }
   /*
     * @method getPopup : get popup menu
     * @param no
     * return popup : JPopupMenu
     */
    public JPopupMenu getPopupDatabase() {
        return popup_database;
    }
    public JPopupMenu getPopupTable() {
        return popup_table;
    }
    public JPopupMenu getPopupServer() {
        return popup_table;
    }
    /*
     * @method dropTable drop table from a database
     * @param database : String 
     * @param Table : String
     * return no
     */
    public void dropTable(String database,String table) {
      DataManager d = new DataManager();
      d.ReadDatabase();
      d.Delete_Table(database, table);
        
    }
       /*
     * @method dropTable drop table from a database
     * @param database : String 
     * @param Table : String
     * return no
     */
     public void dropDatabase(String database)
     {
      DataManager d = new DataManager();
      d.ReadDatabase();
      d.DropDatabase(database);
     }
    /*
     * @Method OpenTable : open table when righ click on tree and choose table
     * example righ click on table HocSinh then chose open
     * @param table : String
     * @param database: String
     * @return No
     */
   private void OpenTable(String table,String database){
      BUS_ParseQuerry demo = new BUS_ParseQuerry(database);
      String strsql = "select * from " + table;
      Bus_Table table1 =  (Bus_Table)demo.ParseQuerry(strsql);
        
      DefaultTableModel model_table = new DefaultTableModel();
      model_table = new DefaultTableModel();
                  
      for(int j = 0;j<table1.tableData.elementAt(0).rowData.size();j++)
       {
               
         model_table.addColumn(table1.tableData.elementAt(0).rowData.elementAt(j).columnName);
       }
           
        for(int i = 0;i<table1.tableData.size();i++)
         {
             Vector data = new Vector();
             for(int j = 0;j<table1.tableData.elementAt(i).rowData.size();j++)
             {
               
                  data.add(table1.tableData.elementAt(i).rowData.elementAt(j).Value);
             }
              model_table.addRow(data);
         }
       JTable jtable = new JTable();
       jtable.setModel(model_table);
       jtable.setPreferredScrollableViewportSize(new Dimension(table1.tableData.elementAt(0).rowData.size()*100,500));
       jtable.setFillsViewportHeight(true);
       
        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane_table = new JScrollPane(jtable);
         splitPaneRight.setSplitPaneTop(scrollPane_table);
         splitPaneRight.getPanelBottom().removeAll();
         splitPaneRight.getSplitPane().setDividerLocation(500);
         pack();
         setVisible(true);
  
   
   }
    private void createTable(String database) {
  
          ModuleTable c = new ModuleTable(database);
          splitPaneRight.setSplitPaneTop(c);
          splitPaneRight.getSplitPane().setDividerLocation(500);
          pack();
          setVisible(true);             
    }
   /*
     * @varible MouseListener
     * appear when we right click 
     * 
     */
    private MouseListener ma = new MouseAdapter() {
        private void checkForPopup(MouseEvent e) {
            if(e.isPopupTrigger()) {
                loc = e.getPoint();
                TreePath path  = jtree.getPathForLocation(loc.x, loc.y);
               
              
                if(path == null) {
                    e.consume();
                    return;
                }
               TreeNode root = (TreeNode)jtree.getModel().getRoot();
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
               if(node.getLevel() == 1)
               {
               
                //overRoot = false;
               popup_server.show(jtree, loc.x, loc.y);
               
               }
               else
                    if(node.getLevel() == 2)
                     {
               
                       //overRoot = false;
                       popup_database.show(jtree, loc.x, loc.y);
               
                      }
                    else
                        {
                            if(node.getLevel() == 3)
                                {
                                //  overRoot1 = false;
                                    popup_table.show(jtree, loc.x, loc.y);
                                 }    
                    
                                      else
                                             {
                                                  // overRoot = true;
                                                  // overRoot1 = true;
                                               }
        }   
        }
        }
 
        public void mousePressed(MouseEvent e)  { checkForPopup(e); }
        public void mouseReleased(MouseEvent e) { checkForPopup(e); }
        public void mouseClicked(MouseEvent e)  { checkForPopup(e); }
    };
  
    public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
      // popup.setVisible(!overRoot);
      // popup1.setVisible(!overRoot1);
    }
 
    public void popupMenuCanceled(PopupMenuEvent e) {}
    public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
    public void loadTree()
    {
      jtree = new JTree(getTreeComponent());
             
        popup_database = new JPopupMenu();
        popup_database.setInvoker(jtree);
        popup_database.add(getMenuItem("Drop Database"));
        popup_database.add(getMenuItem("Create Table"));
        popup_database.add(getMenuItem("Refresh"));
       
        popup_database.addPopupMenuListener(this);
        //set popup for table
        popup_table = new JPopupMenu();
        popup_table.setInvoker(jtree);
     
        popup_table.add(getMenuItem("Open"));
        popup_table.add(getMenuItem("Edit"));
        popup_table.add(getMenuItem("Drop Table"));
        popup_table.add(getMenuItem("Refresh"));
        popup_table.addPopupMenuListener(this);    
        
        //set popup menu for create database and refresh
        popup_server = new JPopupMenu();
        popup_server.setInvoker(jtree);
     
        popup_server.add(getMenuItem("Create Database"));
        popup_server.add(getMenuItem("Refresh"));
       jtree.setCellRenderer(new IconNodeRenderer());
       
    
        // add tree with popup handler
       jtree.add(getPopupDatabase());
       
       jtree.add(getPopupTable());
       jtree.add(getPopupServer());
       jtree.addMouseListener(ma);
    }



    /*
     * @class  MyDocumentListener Manipulate event DocumentListener from a text area
     * Mehods : insetUpdate,RemoveUpdate,chageUpdate 
     * Method  updateLog  set button run enable  if textarea contain char else button run wil be unenable
     */
class MyDocumentListener implements DocumentListener {
        

        public void insertUpdate(DocumentEvent e) {
            updateLog(e);
            jbtnsave.setEnabled(true);
        }
        public void removeUpdate(DocumentEvent e) {
            updateLog(e);
             jbtnsave.setEnabled(true);
        }
        public void changedUpdate(DocumentEvent e) {
            //Plain text components don't fire these events.
             jbtnsave.setEnabled(true);
        }

        public void updateLog(DocumentEvent e) {
            Document doc = (Document)e.getDocument();
          
        if(doc.getLength() > 0)
           jbtnrun.setEnabled(true);
       else
           jbtnrun.setEnabled(false);
            
        }
    }
}
/*
 * Class IconNodeRenderer : render Icon for node
 */
class IconNodeRenderer extends DefaultTreeCellRenderer {

  public Component getTreeCellRendererComponent(JTree tree, Object value,
      boolean sel, boolean expanded, boolean leaf, int row,
      boolean hasFocus) {

    super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
        row, hasFocus);

    Icon icon = ((IconNode) value).getIcon();

    if (icon == null) {
      Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons");
      String name = ((IconNode) value).getIconName();
      if ((icons != null) && (name != null)) {
        icon = (Icon) icons.get(name);
        if (icon != null) {
          setIcon(icon);
        }
      }
    } else {
      setIcon(icon);
    }

    return this;
  }
}

class IconNode extends DefaultMutableTreeNode {

  protected Icon icon;

  protected String iconName;

  public IconNode() {
    this(null);
  }

  public IconNode(Object userObject) {
    this(userObject, true, null);
  }

  public IconNode(Object userObject, boolean allowsChildren, Icon icon) {
    super(userObject, allowsChildren);
    this.icon = icon;
  }

  public void setIcon(Icon icon) {
    this.icon = icon;
  }

  public Icon getIcon() {
    return icon;
  }

  public String getIconName() {
    if (iconName != null) {
      return iconName;
    } else {
      String str = userObject.toString();
      int index = str.lastIndexOf(".");
      if (index != -1) {
        return str.substring(++index);
      } else {
        return null;
      }
    }
  }

  public void setIconName(String name) {
    iconName = name;
  }

}


